<?php

namespace App\Services\Tools;

//require_once VENDOR_PATH . 'aliyuncs/aliyun-oss-php-sdk/autoload.php';
//include_once VENDOR_PATH . 'aliyuncs/aliyun-php-sdk-core/Config.php';

use Illuminate\Support\Facades\Log;

class HelperService {
    public static function curl_gets($url, $get_data = []) {
        //构造请求参数
        $param = http_build_query($get_data);
        $url = $url . '?' . $param;
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($code != 200) return false;
        curl_close($ch);
        return json_decode($output, true);
    }

    public static function CurlPost($url, $post_data = []) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求头
//        curl_setopt($ch, CURLOPT_HEADER, $header);
        //设置请求方式为POST
        curl_setopt($ch, CURLOPT_POST, true);
        //post变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        //输出
        $output = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($code != 200) {
            return ['code' => $code, 'data' => false];
        }
        curl_close($ch);
        return json_decode($output, true);
    }


    public static function todayLeftTime() {
        return (strtotime(date('Ymd')) + 86400 - time());
    }
    //盲盒价格
    public static function blindBoxPrice(){
        $price =[
            'gold'=>600,
            'silver'=>2100,
            'copper'=>600,
        ];
        return $price;
     }


    public static function giftRank($money = 0) {
        if ($money < 500) {
            return '白色';
        } elseif ($money >= 500 && $money < 5000) {
            return '绿色';
        } elseif ($money >= 5000 && $money <= 29998) {
            return '蓝色';
        } elseif ($money > 29998 && $money < 200000) {
            return '紫色';
        } else {
            return '橙色';
        }
    }


    public static function arraySort($array, $keys, $sort = 'asc') {
        $newArr = $valArr = [];
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ? asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return $newArr;
    }

    //mode: 1get 2post
    public static function httpRequest($url, $data = [], $mode = 1, $header = []) {
        $headers = [
            "Content-Type: application/json; charset=utf-8",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache"
        ];
        if (!empty($header)) {
            $headers = array_merge($headers, $header);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); //设置超时

        if ($mode == 2) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_FORCE_OBJECT));
        } else {
            if ($data) {
                $querystring = http_build_query($data);
                $url = $url . '?' . $querystring;
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }


    //数字格式话
    public static function numberFormat($number) {
        $num = bcdiv($number, 10000, 2);
        if ($num > 1) {
            $number = $num . 'w';
        }
        return $number;
    }

    /**
     * @param $time 单位：s
     */
    public static function time_format($time) {
        $str = '';
        if ($time >= 86400) {
            $day = floor(bcdiv($time, 86400));
            $time = bcmod($time, 86400);
            $str .= $day . '天';
        }
        if ($time >= 3600) {
            $hour = floor(bcdiv($time, 3600));
            $time = bcmod($time, 3600);
            $str .= $hour . '小时';
        } else {
            $hour = 0;
        }
        if ($time >= 60) {
            $minute = floor(bcdiv($time, 60));
            $second = bcmod($time, 60);
            $str .= $minute . '分' . $second . '秒';
        } else {
            $second = $time;
            $str .= $second . "秒";
        }
        return $str;

    }

    /**
     * 判断六一活动是否开始
     */
    public static function checkActivityTime() {
        $begin_time = strtotime('2020-06-24 22:00:00');
        $end_time = strtotime('2020-06-27 23:59:59');
        $time = NOW_TIME;
        if ($time < $begin_time || $time > $end_time) {
            return false;
        } else {
            return true;
        }
    }

    public static function is_weixin_visit() {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }

    //判断是否模拟器
    public static function is_emulator($emulator) {
        return $emulator == 1;
    }


    /**
     * 过滤文本，只保留中文、数字、英文、空格
     * @param $str
     * @return mixed
     */
    public static function filterTxt($str) {
        $face = ['[):]', '[:D]', '[;)]', '[:-o]', '[:p]', '[(H)]', '[:@]', '[:s]', '[:$]', '[:(]', "[:'(]", '[(a)]', '[8o|]', '[8-|]', '[+o(]', '[<o)]', '[|-)]', '[*-)]', '[:-#]', '[:-*]', '[^o)]', '[8-)]', '[(|)]', '[(u)]', '[(S)]', '[(*)]', '[(#)]', '[(R)]', '[({)]', '[(})]', '[(k)]', '[(F)]', '[(W)]', '[(D)]'];

        $str = str_replace($face, '', $str);
        preg_match_all('/[\x{4e00}-\x{9fa5}\d\w\s]+/u', $str, $result);
        $result = join('', $result[0]);
        $result = trim($result);
        return $result;
    }



    public static function exportCsv($header = [], $data = [], $filename = '') {
        ini_set('memory_limit', '1024M'); //设置程序运行的内存
        ini_set('max_execution_time', 0); //设置程序的执行时间,0为无上限
        ob_end_clean();                   //清除内存
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . $filename . '.csv');
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        fputcsv($fp, $header);
        $index = 0;
        foreach ($data as $item) {
            if ($index == 5000) { //每次写入1000条数据清除内存
                $index = 0;
                ob_flush();//清除内存
                flush();
            }
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
        exit();
    }

    /**
     * 请求新lumen框架获取数据
     * @param $api_name
     * @param $data
     * @param string $type
     * @return mixed
     */
    public static function lumenApi($api_name, $data, $type = 'post') {
        if (env('APP_ENV') == 'local') {
            $url = env('LOCAL_NAPI_HOST');
        } else {
            $url = env('PRODUCTION_NAPI_HOST');
        }
        $url = $url . '/' . trim($api_name, '/');
        if ($type == 'post') {
            $result = static::CurlPost($url, $data);
        } else {
            $result = static::curl_gets($url, $data);
        }
        return $result;
    }


    //获取国庆活动头像框id
    public function  headPictureIds(){
        //最后一个为坐骑id
        $ids = [57,58,59,60];
        return $ids;
    }

    //获取国庆活动兑换头像框
    public function  exchangeHeaderPic(){
        $ids = [54,55,56];
        return $ids;
    }

    //国庆活动钥匙扣名称
    public  function   keyBuckleName(){
        $names =['钥匙扣1号','钥匙扣2号','钥匙扣3号','钥匙扣4号','钥匙扣5号','钥匙扣6号'];
        return $names;
    }
    //国庆活动兑换钥匙扣需要的积分
    public  function  buckleScore(){
        $score =['90000','100000','110000','120000','130000','140000'];
        return $score;
    }

    //国庆活动抱枕被名称
    public  function   pillowName(){
        $names =['抱枕被1号','抱枕被2号','抱枕被3号','抱枕被4号','抱枕被5号'];
        return $names;
    }

    //国庆活动抱枕被兑换需要积分
    public  function   exchangePillowScore(){
        $score =['180000','190000','200000','210000','220000'];
        return $score;
    }

    public static function getHeaders() {
        $headers = [];
        if (function_exists('apache_request_headers') && $result = apache_request_headers()) {
            $headers = $result;
        } else {
            foreach ($_SERVER as $key => $val) {
                if (0 === strpos($key, 'HTTP_')) {
                    $key = str_replace('_', '-', strtolower(substr($key, 5)));
                    $headers[$key] = $val;
                }
            }
        }
        $headers = array_change_key_case($headers);
        return $headers;
    }

    //出生日期转年龄
    public static function birthToAge($birth, $type = false) {
        if($birth == '0000-00-00') return 0;
        if ($type) $birth = strtotime($birth);

        //格式化出生时间年月日
        $byear = date('Y', $birth);
        $bmonth = date('m', $birth);
        $bday = date('d', $birth);

        //格式化当前时间年月日
        $tyear = date('Y');
        $tmonth = date('m');
        $tday = date('d');

        //开始计算年龄
        $age = $tyear - $byear;
        if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
            $age--;
        }
        return $age;
    }

    //获取随机昵称
    public static function getRandomNickname() {
        return '用户';
        return static::getRandomChinese(1) . static::getRandomChinese(2);
    }

    //获取随机中文
    //$type = 1获取随机姓 $type = 2 获取随机名
    private static function getRandomChinese($type)
    {
        if ($type == 1) {
            $redis_key = 'random:lastname';
            $filename = 'random_last_name.txt';
        } else {
            $redis_key = 'random:firstname';
            $filename = 'random_first_name.txt';
        }

        if (!app('redis')->exists($redis_key)) {
            $file = fopen(base_path() . "/{$filename}", "r");
            $result = [];
            while (!feof($file)) {
                $result[] = str_replace(["\s", "\r", "\n"], '', fgets($file));
            }
            fclose($file);
            app('redis')->sadd($redis_key, ...$result);
            return $result[mt_rand(0, count($result) - 1)];
        } else {
            return app('redis')->srandmember($redis_key);
        }
    }


    public static function getRandomHeadPicture() {
        $arr = [
            'https://biluo-cs.oss-cn-hangzhou.aliyuncs.com/avatar/default.png',
        ];
        return $arr[mt_rand(0, count($arr) - 1)];
    }

    public static function microtime_float()
    {
        //        $microTime = microtime() * 10000000;
        //        $microTime = substr($microTime, 0, 6);
        //        return time() . $microTime;
        return (int)(microtime(true) * 1000);
    }
}
